package com.bsg.upm.service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.constant.SysConstants;
import com.bsg.upm.dto.SubServParameterConfigDto;
import com.bsg.upm.entity.ServEntity;
import com.bsg.upm.entity.SubServEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;

/**
 * 子服务参数配置业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class SubServParamterConfigService extends BaseService {

	/**
	 * 获取指定服务下的指定子服务参数配置
	 * 
	 * @param servId
	 *            服务编码
	 * @param subServType
	 *            子服务类型
	 * @return RespJson请求结果
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(String servId, String subServType) throws APIException {
		try {
			JSONArray retJsonArray = new JSONArray();
			// 获取指定的服务
			ServEntity serv = servDao.getBase(servId);
			if (serv == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该服务不存在");
			}

			// 站点
			String siteId = serv.getOrder().getArea().getSite().getId();
			List<SubServEntity> subServs = serv.getSubServs();
			for (SubServEntity subServ : subServs) {
				// 子服务类型
				String type = subServ.getSubOrder().getDefinitionSubServ().getName();
				if (type.equals(subServType)) {
					if (StringUtils.isNotBlank(subServ.getRelateId())) {
						// 从MGM获取配置文件信息
						JSONArray mgmServConfigInfos = getConfigFromMGM(siteId, subServ.getRelateId());
						if (mgmServConfigInfos != null && mgmServConfigInfos.size() > 0) {
							JSONArray mgmKeysetsInfo = mgmServConfigInfos.getJSONObject(0).getJSONArray("keysets");
							for (int i = 0; i < mgmKeysetsInfo.size(); i++) {
								JSONObject mgmKeysetInfo = mgmKeysetsInfo.getJSONObject(i);
								SubServParameterConfigDto configDto = buildShowDto(mgmKeysetInfo);
								retJsonArray.add(configDto);
							}
						}
						break;
					}
				}
			}

			return RespJsonFactory.buildOK(retJsonArray);
		} catch (Exception e) {
			logger.error("子服务参数查询异常", e);
			throw new APIException("子服务参数查询异常:" + e.getMessage());
		}
	}

	/**
	 * 获取指定服务下的指定子服务参数配置
	 * 
	 * @param servId
	 *            服务编码
	 * @param subServType
	 *            子服务类型
	 * @param paramMaps
	 *            请求参数
	 * @return RespJson请求结果
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson update(String servId, String subServType, List<Map<String, Object>> paramMaps) throws APIException {
		try {
			// 获取指定的服务
			ServEntity serv = servDao.getBase(servId);
			if (serv == null) {
				return RespJsonFactory.build(HttpStatus.SC_GONE, "该服务不存在");
			}

			// 站点
			String siteId = serv.getOrder().getArea().getSite().getId();
			List<SubServEntity> subServs = serv.getSubServs();
			for (SubServEntity subServ : subServs) {
				// 子服务类型
				String type = subServ.getSubOrder().getDefinitionSubServ().getName();
				if (type.equals(subServType)) {
					String jsonParam = buildUpdateConfigParam(paramMaps);
					updateConfigToMGM(siteId, subServ.getRelateId(), jsonParam);
				}
			}
			return RespJsonFactory.buildOK();
		} catch (Exception e) {
			logger.error("子服务参数编辑异常", e);
			throw new APIException("子服务参数编辑异常:" + e.getMessage());
		}
	}

	/**
	 * 从MGM获取配置文件信息
	 * 
	 * @param siteId
	 *            站点编码
	 * @param mgmServId
	 *            mgm服务编码
	 * @return JSONArray配置文件信息
	 * @throws APIException
	 *             API异常处理类
	 */
	private JSONArray getConfigFromMGM(String siteId, String mgmServId) throws APIException {
		String urlPattern = "/{0}/services/{1}/configs?canset=true";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, mgmServId);
		RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_MGM, url);
		if (httpRespJson.getStatus() == HttpStatus.SC_OK) {
			return ((JSONArray) httpRespJson.getData());
		} else {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * 更新MGM指定服务的配置文件信息
	 * 
	 * @param siteId
	 *            站点编码
	 * @param mgmServId
	 *            mgm服务编码
	 * @param jsonParam
	 *            配置文件参数
	 * @throws APIException
	 *             API异常处理类
	 */
	private void updateConfigToMGM(String siteId, String mgmServId, String jsonParam) throws APIException {
		String urlPattern = "/{0}/services/{1}/config/update";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION, mgmServId);
		RespJson httpRespJson = sendHttpPost(siteId, SysConstants.INTERFACE_TYPE_MGM, url, jsonParam);
		if (httpRespJson.getStatus() != HttpStatus.SC_CREATED) {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	/**
	 * 构建更新配置文件参数
	 * 
	 * @param paramMaps
	 *            请求参数
	 * @return 配置文件参数
	 */
	private String buildUpdateConfigParam(List<Map<String, Object>> paramMaps) {
		JSONObject json = new JSONObject();
		JSONArray keysetJsonArr = new JSONArray(paramMaps.size());
		json.put("keysets", keysetJsonArr);
		for (Map<String, Object> paramMap : paramMaps) {
			JSONObject keysetJson = new JSONObject();
			keysetJson.put("key", (String) paramMap.get("name"));
			keysetJson.put("value", (String) paramMap.get("value"));
			keysetJsonArr.add(keysetJson);
		}
		return json.toJSONString();
	}

	/**
	 * 构建子服务配置文件展示
	 * 
	 * @param mgmKeysetInfo
	 *            mgm配置文件信息
	 * @return 子服务配置文件展示对象
	 */
	private SubServParameterConfigDto buildShowDto(JSONObject mgmKeysetInfo) {
		SubServParameterConfigDto configDto = new SubServParameterConfigDto();
		configDto.setName(mgmKeysetInfo.getString("key"));
		configDto.setValue(mgmKeysetInfo.getString("value"));
		configDto.setMustRestart(mgmKeysetInfo.getBoolean("must_restart"));
		configDto.setDescription(mgmKeysetInfo.getString("desc"));
		return configDto;
	}
}
